﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Ch13CardLib;
using Ch13CardLib.enums;
using KarliCardsGui.Converters;
using KarliCardsGui.Animations;
using KarliCardsGui.ViewModels;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace KarliCardsGui
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly ShuffleAnimator shuffleAnimator = new ShuffleAnimator();
        private bool isShuffling = false;
        private bool isGameStarted = false;
        private DispatcherTimer countdownTimer;
        private int countdownSeconds = 10;
        private int steps = 0;  // 添加步数计数器
        private CardViewModel firstCard = null;  // 第一张翻开的牌
        private CardViewModel secondCard = null; // 第二张翻开的牌
        private DispatcherTimer matchTimer;      // 用于不匹配时的延迟
        private bool isAnimating = false;  // 添加动画状态标志

        public MainWindow()
        {
            InitializeComponent();
            
            // 初始化计时器
            countdownTimer = new DispatcherTimer();
            countdownTimer.Interval = TimeSpan.FromSeconds(1);
            countdownTimer.Tick += CountdownTimer_Tick;
            
            // 初始化匹配检查计时器
            matchTimer = new DispatcherTimer();
            matchTimer.Interval = TimeSpan.FromSeconds(1);
            matchTimer.Tick += MatchTimer_Tick;
            
            // 注册刷新卡牌的委托
            RandomCardBackConverter.RefreshCards = RefreshCardsHandler;
        }

        private async void ShuffleDeck_Click(object sender, RoutedEventArgs e)
        {
            if (isShuffling) return;
            isShuffling = true;

            var viewModel = (MainViewModel)DataContext;
            var cards = new List<CardViewModel>();

            if (isGameStarted)
            {
                // 1. 收集所有卡牌（包括游戏区域和右侧区域的牌）
                var gameCards = GameArea.ItemsSource as List<CardViewModel>;
                if (gameCards != null)
                {
                    cards.AddRange(gameCards.Where(c => c != null));
                }
                // 添加右侧区域的牌
                cards.AddRange(viewModel.Cards);

                GameArea.ItemsSource = null;  // 清空游戏区域
                viewModel.Cards.Clear();      // 清空右侧区域

                // 2. 将所有卡牌翻转为背面朝上
                foreach (var card in cards)
                {
                    card.IsFaceUp = false;
                    card.IsClickable = false;  // 重置点击状态
                }

                // 3. 将卡牌放回右侧区域
                foreach (var card in cards)
                {
                    viewModel.UpdateCardPosition(card);
                    viewModel.Cards.Add(card);
                }

                // 4. 重置游戏状态
                isGameStarted = false;
                StartButton.IsEnabled = true;

                // 等待一小段时间让卡牌回到位置
                await Task.Delay(500);
            }
            else
            {
                cards = viewModel.Cards.ToList();
            }

            // 5. 执行洗牌动画
            await shuffleAnimator.AnimateShuffleAsync(cards);

            viewModel.Cards.Clear();
            foreach (var card in cards)
            {
                viewModel.UpdateCardPosition(card);
                viewModel.Cards.Add(card);
            }

            isShuffling = false;
        }

        private void RefreshCardsHandler(List<CardViewModel> cards)
        {
            // 获取当前视图模型
            var viewModel = (MainViewModel)DataContext;
            
            // 刷新右侧区域的卡牌
            var rightCards = viewModel.Cards.ToList();
            viewModel.Cards.Clear();
            foreach (var card in rightCards)
            {
                card.IsFaceUp = card.IsFaceUp; // 触发属性变更通知
                viewModel.Cards.Add(card);
            }
            
            // 刷新游戏区域的卡牌
            if (isGameStarted)
            {
                var gameCards = GameArea.ItemsSource as List<CardViewModel>;
                if (gameCards != null)
                {
                    foreach (var card in gameCards)
                    {
                        if (card != null)
                        {
                            card.IsFaceUp = card.IsFaceUp; // 触发属性变更通知
                        }
                    }
                    
                    // 强制刷新ItemsControl
                    GameArea.Items.Refresh();
                }
            }
        }

        private void ChangeCardBackground_Click(object sender, RoutedEventArgs e)
        {
            // 只需调用更换背景方法，刷新卡牌的工作会通过委托完成
            KarliCardsGui.Converters.RandomCardBackConverter.ChangeBackground();
        }

        private void CountdownTimer_Tick(object sender, EventArgs e)
        {
            countdownSeconds--;
            CountdownText.Text = $"请记住牌\n({countdownSeconds}S)";

            if (countdownSeconds <= 0)
            {
                // 停止计时器
                countdownTimer.Stop();
                steps = 0;  // 重置步数
                CountdownText.Text = $"操作步数\n({steps})";  // 显示步数
                
                // 将所有卡牌翻转为背面并添加点击事件
                var viewModel = (MainViewModel)DataContext;
                var gameCards = GameArea.ItemsSource as List<CardViewModel>;
                if (gameCards != null)
                {
                    foreach (var card in gameCards)
                    {
                        if (card != null)
                        {
                            card.IsFaceUp = false;
                            card.IsClickable = true;  // 启用点击
                        }
                    }
                }
            }
        }

        private void MatchTimer_Tick(object sender, EventArgs e)
        {
            matchTimer.Stop();
            // 翻回两张不匹配的牌
            if (firstCard != null) firstCard.IsFaceUp = false;
            if (secondCard != null) secondCard.IsFaceUp = false;
            firstCard = null;
            secondCard = null;
        }

        private void Card_Click(object sender, RoutedEventArgs e)
        {
            if (!isGameStarted || countdownTimer.IsEnabled || matchTimer.IsEnabled || isAnimating) return;

            var cardControl = sender as CardControl;
            if (cardControl != null)
            {
                var card = cardControl.DataContext as CardViewModel;
                if (card != null && !card.IsFaceUp && card.IsClickable)
                {
                    card.IsFaceUp = true;
                    steps++;
                    CountdownText.Text = $"操作步数\n({steps})";

                    // 处理卡牌匹配逻辑
                    if (firstCard == null)
                    {
                        firstCard = card;
                    }
                    else if (secondCard == null && card != firstCard)
                    {
                        secondCard = card;
                        
                        // 检查是否匹配
                        if (firstCard.Rank == secondCard.Rank)
                        {
                            // 匹配成功，移动到右侧
                            MoveCardsToRightArea();
                        }
                        else
                        {
                            // 不匹配，1秒后翻回
                            matchTimer.Start();
                        }
                    }
                }
            }
        }

        private async void MoveCardsToRightArea()
        {
            isAnimating = true;  // 设置动画开始标志
            try
            {
                var viewModel = (MainViewModel)DataContext;
                var gameCards = GameArea.ItemsSource as List<CardViewModel>;

                if (gameCards != null)
                {
                    // 禁用这两张牌的点击
                    firstCard.IsClickable = false;
                    secondCard.IsClickable = false;

                    // 等待一段时间让用户看清匹配的牌
                    await Task.Delay(500);

                    // 从游戏区域移除这两张牌
                    int firstIndex = gameCards.IndexOf(firstCard);
                    int secondIndex = gameCards.IndexOf(secondCard);
                    gameCards[firstIndex] = null;
                    gameCards[secondIndex] = null;

                    // 添加到右侧区域并设置位置
                    await AnimateCardToRightArea(firstCard);
                    await AnimateCardToRightArea(secondCard);

                    // 刷新游戏区域显示
                    GameArea.ItemsSource = null;
                    GameArea.ItemsSource = gameCards;

                    // 重置卡牌引用
                    firstCard = null;
                    secondCard = null;

                    // 检查游戏是否结束
                    if (!gameCards.Any(c => c != null))
                    {
                        MessageBox.Show($"恭喜！您用了 {steps} 步完成了游戏！", "游戏结束", MessageBoxButton.OK);
                        StartButton.IsEnabled = true;
                        isGameStarted = false;
                        
                        // 游戏结束后自动洗牌
                        await Task.Delay(500);  // 等待消息框关闭
                        ShuffleDeck_Click(null, null);
                    }
                }
            }
            finally
            {
                isAnimating = false;  // 确保动画标志被重置
            }
        }

        private async Task AnimateCardToRightArea(CardViewModel card)
        {
            var viewModel = (MainViewModel)DataContext;
            
            // 计算目标位置
            double targetX = 20;
            double targetY = 20 + (viewModel.Cards.Count * 10);
            
            // 记录起始位置
            double startX = card.XPosition;
            double startY = card.YPosition;
            
            // 添加到右侧区域
            viewModel.Cards.Add(card);
            
            // 执行移动动画
            const int animationDuration = 500; // 500毫秒
            DateTime startTime = DateTime.Now;
            
            CompositionTarget.Rendering += Animate;
            
            void Animate(object sender, EventArgs e)
            {
                double elapsed = (DateTime.Now - startTime).TotalMilliseconds;
                if (elapsed >= animationDuration)
                {
                    card.XPosition = targetX;
                    card.YPosition = targetY;
                    card.ZIndex = viewModel.Cards.Count - 1;
                    CompositionTarget.Rendering -= Animate;
                    return;
                }

                double progress = elapsed / animationDuration;
                card.XPosition = startX + (targetX - startX) * progress;
                card.YPosition = startY + (targetY - startY) * progress;
            }

            // 等待动画完成
            await Task.Delay(animationDuration);
        }

        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            steps = 0;  // 重置步数
            var viewModel = (MainViewModel)DataContext;
            var cards = viewModel.Cards.ToList();
            viewModel.Cards.Clear();

            // 创建55个位置（11x5=55）
            var gameCards = new List<CardViewModel>();
            
            // 前52个位置放置卡牌，并设置正面朝上
            for (int i = 0; i < 52; i++)
            {
                var card = cards[i];
                card.IsFaceUp = true;
                card.IsClickable = false;  // 禁用点击
                gameCards.Add(card);
            }

            // 后3个位置不添加卡牌
            for (int i = 52; i < 55; i++)
            {
                gameCards.Add(null);
            }

            // 设置到游戏区域
            GameArea.ItemsSource = gameCards;
            
            // 禁用开始按钮并设置游戏状态
            StartButton.IsEnabled = false;
            isGameStarted = true;

            // 开始倒计时
            countdownSeconds = 10;
            CountdownText.Text = $"请记住牌\n({countdownSeconds}S)";
            CountdownText.Visibility = Visibility.Visible;
            countdownTimer.Start();
        }
    }
}